package com.awesome.spring.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.awesome.spring.bean.Order;
import com.awesome.spring.feign.AccountFeign;
import com.awesome.spring.mapper.OrderMapper;
import com.awesome.spring.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * OrderServiceImpl
 *
 * @author alex
 * @date 2022/07/07
 */

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private AccountFeign accountFeign;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void create(String userId, int money, boolean rollback) {
        String orderCode = UUID.randomUUID().toString();

        Order order = new Order();
        order.setCode(orderCode);
        order.setCount(1);
        order.setUserId(userId);
        order.setMoney(money);

        this.save(order);

        // 有问题就不发出请求
        if (rollback) {
            int a = 1/0;
        }

        String result = accountFeign.debit(userId, money);

        System.out.println("扣减余额结果：" + result);

        if (!"扣款成功".equals(result)) {
            throw new RuntimeException("扣减余额失败");
        }

        // 后面不要执行复杂的逻辑，避免 account 钱扣了，但是订单没有生成
       /* if (rollback) {
            int a = 1/0;
        }*/

    }
}
